using System;
using System.Web;
using System.IO;
using System.Web.Hosting;
using System.Drawing;
using System.Drawing.Imaging;

using MvcCms.Service.Code;
using MvcCms.Service.Cache;

namespace MvcCmsSocial.Models
{
    internal class DiskFileStore : IFileStore
    {
        #region Constructors
        private readonly ICacheService _cacheService;

        public DiskFileStore(ICacheService cacheService)
        {
            _cacheService = cacheService;
        }
        #endregion
        public string SaveUploadedFile(HttpPostedFileBase fileBase)
        {
            var identifier = Guid.NewGuid();
            string foldername = _cacheService.GetCurrentPortal().Name.ToUrlFormat();
            if (fileBase.FileName.Contains("jpg") ||
                fileBase.FileName.Contains("gif") ||
                fileBase.FileName.Contains("png"))
            {
                string path = HostingEnvironment.MapPath("~/Uploadedimages/" + foldername + "/Profiles");
                Directory.CreateDirectory(path);
                string extension = StringUtils.ExtractString(fileBase.FileName, ".", "justgotoend", false, true);
                string filePath = Path.Combine(path, identifier.ToString() + "." + extension);
                fileBase.SaveAs(filePath);

                //convert the image to jpeg
                var bmpIn = (Bitmap)Bitmap.FromFile(filePath);
                var cropedImage = new Bitmap(bmpIn.Width, bmpIn.Height, PixelFormat.Format24bppRgb);

                using (var g = Graphics.FromImage(cropedImage))
                {
                    var rec = new Rectangle(0, 0, bmpIn.Width, bmpIn.Height);
                    g.DrawImage(bmpIn, rec, 0, 0, bmpIn.Width, bmpIn.Height, GraphicsUnit.Pixel);
                }
                bmpIn.Dispose();
                //Delete the original
                File.Delete(filePath);
                identifier = Guid.NewGuid();
                filePath = Path.Combine(path, identifier.ToString() + ".jpg");
                cropedImage.Save(filePath, ImageFormat.Jpeg);

                string thumbPath = HostingEnvironment.MapPath("~/Uploadedimages/" + foldername + "/Profiles/thumbs");
                Directory.CreateDirectory(thumbPath);
                thumbPath = Path.Combine(thumbPath, identifier.ToString() + ".jpg");
                Files.ResizeImage(filePath, thumbPath, 80, 300, false);
                return identifier + ".jpg";
            }
            return null;
        }
    }
}